﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using IceScream.Models;
using IceScream.ViewModels;

namespace IceScream.Controllers
{
     [Authorize(Users = "admin")]
    public class CatManagerController:Controller
    {
        DataEntities storeDB = new DataEntities();
        public ActionResult Index()
        {
            var Cats = storeDB.Categories.ToList();
            return View(Cats);
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(Category pCat)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    storeDB.AddToCategories(pCat);
                    storeDB.SaveChanges();
                    return RedirectToAction("index");
                }
                return View();
            }
            catch
            {
                return View();
            }
        }

        public ActionResult Edit(int id)
        {
            var cats = storeDB.Categories.Where(a => a.Id == id).FirstOrDefault();

            var viewModels = new CatManagerViewModels
            {
                Category = cats
            };

            return View(viewModels);
        }

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            var cats = storeDB.Categories.Where(a => a.Id == id).FirstOrDefault();
            if (ModelState.IsValid)
            {
                UpdateModel(cats, "Category");
                storeDB.SaveChanges();

                return RedirectToAction("index");
            }

            var viewModels = new CatManagerViewModels
            {
                Category = cats
            };

            return View(viewModels);
        }

        [HttpGet]
        public ActionResult Delete(int id, FormCollection collection)
        {
            // delete category
            var cat = storeDB.Categories.Single(a => a.Id == id);

            storeDB.DeleteObject(cat);
            storeDB.SaveChanges();

            return RedirectToAction("index");
        }
    }
}